import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,DatePicker ,Toast ,Button,TextareaItem,WhiteSpace,Checkbox,Modal} from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail} from '../../utils/Validator.js'
import options from '../../models/CityData.js'
import PropTypes from 'prop-types';
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import moment from 'moment';
import 'moment/locale/zh-cn';
import {reqwest_get,reqwest_post} from '../../utils/Reqwest.js';
const AgreeItem = Checkbox.AgreeItem;
const maxTime = moment('22:00 +0800', 'HH:mm Z').utcOffset(8);
const minTime = moment('08:30 +0800', 'HH:mm Z').utcOffset(8);
// let _option={};
class OrderEdit extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:false,
      companies:sessionStorage['companies']===undefined||'undefined'?[]:JSON.parse(sessionStorage['companies']),
      material:localStorage['material']===undefined||localStorage['material']=='undefined'?[]:JSON.parse(localStorage['material']),
      cgj_id:window.localStorage['cgj_id']=='null'||window.localStorage['cgj_id']==null||window.localStorage['cgj_id']==undefined||window.localStorage['cgj_id']=='undefined'?false:true,
      // surveyors:window.sessionStorage['surveyors']===undefined?[]:JSON.parse(window.sessionStorage['surveyors']),
      shifu:[],
      surveyors:[],
      // store_tree:sessionStorage['store_tree']===undefined||'undefined'?[]:JSON.parse(sessionStorage['store_tree']),
      sto_col:undefined,
      loading:false
		}
	}
  getServer(){
    // debugger;
    // this.setState({loading:true});
    reqwest_get('/api/pres',{
      access_token:window.localStorage['token']
    },(data)=>{
      if(data.status=='success'){
        this.setState({companies:data.select_companies,store_tree:data.stores_tree});
      }else{
        Toast.fail(data.msg)
      }
    })
    // reqwest({
    //   url: window.host+'/api/pres',
    //   method: 'get',
    //   crossOrigin: true,
    //   // headers:AUTH_KEY,
    //   // contentType: 'application/json',
    //   data:{
    //     access_token:window.localStorage['token']
    //   },
    //   type: 'json',
    // }).then((data) => {
    //   console.log(data);
    //   // sessionStorage['companies']=JSON.stringify(data.companies);
    //   // sessionStorage['material']=JSON.stringify(data.libs);
      

    // }).fail( (err, msg) =>{
    //    console.log(1)
    //    // this.setState({loading:true});
    // })
  }
	loadServer(params={}){
		// console.log(params)
		const _this = this;
    this.setState({loading:true})
    // let _
    reqwest_post('/api/orders',{  access_token:localStorage['token'],
        order:{expected_square:params.square,booking_date:params.booking_date,cgj_company_id:JSON.parse(params.cgj_company_id[0]).a,
          material:JSON.parse(params.material[0]).a,material_id:JSON.parse(params.material[0]).b,region_id:params.regions_id[0],store_id:params.regions_id.length<=1?null:params.regions_id[1],
          introducer_name:params.introducer_name,introducer_tel:params.introducer_tel,total:params.total,estimated_total:params.estimated_total,
          cgj_customer_service_id:_this.state.surveyors.id,measure_master:_this.state.surveyors.name},
        customer:{name:params.contact,tel:params.phone.replace(/\s+/g, ""),province:params.province[0],city:params.province[1],area:params.province[2],street:params.address}
      },(data)=>{
        if(data.status=='success'){
            Toast.success(
            '保存成功',
            1,
            ()=>{
              this.setState({loading:false})
              window.location.hash='/hfive/orders';
            }
          )
        }else{
          Toast.fail(
            data.msg,
            1,
            ()=>{
              this.setState({loading:false})
            }
          )
        }
      })
      this.setState({loading:false})
		// reqwest({
  //     url: window.host+'/api/orders',
  //     method: 'post',
  //     crossOrigin: true,
  //     type: 'json',
  //     data:
  //   }).then((data) => {
  //     if(data.status=='success'){
  //         Toast.success(
  //         '保存成功',
  //         1,
  //         ()=>{
  //           window.location.hash='/hfive/orders';
  //         }
  //       )
        
  //     }else{
  //       Toast.fail(
  //         data.msg,
  //         1
  //       )
  //     }
  //   }).fail( (err, msg) =>{
  //      Toast.offline('网络连接失败!!!', 1);
  //   });
	}
  handleSearch(e){
    reqwest_get('/api/orders/fetch_users',{
      access_token:window.localStorage['token'],
      keyword:e
    },(data)=>{
      if (data.status==='success') {
        // console.log(data.surveyors)
        this.setState({shifu:data.surveyors})
      }
    })
  }
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
        // console.log(JSON.parse(values.cgj_company_id[0]).a);
      if (!err  ) {
        console.log('Received values of form: ', values);
      	_this.loadServer(values)
      }else{
        Toast.fail('订单信息位必填项')
      }
    });
	}
	componentWillMount(){
    this.getServer();
    // reqwest_post('http://localhost:3000/db',{id:'123'})

	}
  OkChange(e){
    let _this = this;
    // console.log(e.target.value)
    // return
    // if(!this.state.cgj_id){
      reqwest_get('/api/auth/cgj',{access_token:localStorage['token']},(data)=>{
        if(data.status=='success'){
          window.localStorage['cgj_id']=data.current_user.cgj_user_id;
          _this.setState({cgj_id:true});
          Toast.success('授权成功', 0.5,()=>{
            // window.location.hash='/app/orders'
            // window.localStorage['cgj_id']=data
          })
        }else{
          _this.setState({cgj_id:false});
          Toast.fail('服务器出错啦', 0.5);
        }
      })
    // }
  }
  handleClick(_html,_id){
    console.log(_id)
    this.setState({surveyors:_id,disable:false})
  }
  handleCheck(e){
    // console.log(e.target.checked)
    // return
    if(this.state.cgj_id==false){
      Modal.alert('取消', '确定授权', [
        { text: '取消', onPress: () => console.log(e.target.value) },
        { text: '确定', onPress: ()=> this.OkChange(e) },
      ]) 
    }else{
      this.setState({cgj_id:false})
    }
  }
	render(){
		console.log(this.state.list)
    const { getFieldProps,getFieldError ,getFieldValue,setFields,getFieldsValue,getFieldsError } = this.props.form;
		const _this =this;
    const _companies =[];
    const _material=[];
    const _regionNode = [];
    const _surveyors=[];
    let _storeNode = [];
    let _falg=false;
    let _daaName,_daaId;
    // _option=[]
    this.state.companies.map(function(data,index,obj){
      _companies.push({
        label:data.name,
        value:'{"a":'+data.cgj_id+',"b":'+index+'}',
      })
    })
    this.state.material.map(function(data,index,obj){
      _material.push({
        label:data.name,
        value:'{"a":"'+data.name+'","b":"'+data.id+'"}'
      })
    })
    // this.state.surveyors.map(function(data,index,obj){
    //   _surveyors.push({
    //     label:data.name,
    //     value:data.id
    //   })
    // })
    console.log(this.state.companies)
    if(this.state.sto_col!=undefined){

      this.state.companies[this.state.sto_col.b].stores_tree.map((data,index,obj)=>{
        // console.log(data)
        _storeNode = [];
        data.children.map((_data)=>{
          console.log(_data)
          _storeNode.push({
            label:_data.name,
            value:_data.id, 
          })
        })
        _regionNode.push({
          label:data.name,
          value:data.id,
          children:_storeNode
        })
      })
    }
    // console.log(!!getFieldValue("contact"))
    // if(!!getFieldValue("contact")){
    //   // console.log(getFieldsValue()==typeof({}))
    //   for(let i in getFieldsError()){
    //     console.log(getFieldValue(''+i))
    //     // _falg =getFieldError(""+i)!=undefined||getFieldError(""+i).length===0?true:false;
    //     if (getFieldError(""+i)!=undefined) {
    //       _falg=getFieldValue(''+i)!==undefined?true:false
    //     }else{
    //       _falg=true
    //     }
    //     console.log(_falg)
    //   }
    // }
		return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '订单信息'}>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('contact')}
            onErrorClick={() => {
              alert(getFieldError('contact').join('、'));
            }}
            {...getFieldProps('contact',{
              initialValue:this.props.location.query.name,
              rules:[{required:true,message:'客户姓名'}]
            })}
            placeholder="客户姓名"
          >联系人</InputItem>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('phone')}
            onErrorClick={() => {
              alert(getFieldError('phone').join('、'));
            }}
            {...getFieldProps('phone',{
              initialValue:this.props.location.query.mobile,
              rules:[{required:true,message:'请输入手机号码',len:11,validator:(rule,value,callback)=>{
                !!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
              }}]
            })}
            type='phone'
            placeholder="手机号码"
          >手机号码</InputItem>
          <Picker   extra={<span>地址</span>} style={{textAlign:'left'}} clear
            className={`${Reset.tel_picker}`}
            error={!!getFieldError('province')}
            onErrorClick={() => {
              alert(getFieldError('province').join('、'));
            }}
            placeholder="选择地址"
            onOk={(e)=>{this.setState({disable:false});console.log(e)}}
            {...getFieldProps('province',{
              rules:[{required:true,message:'请选择地址'}]
            })}  title="选择地址" data={options} >
            <List.Item arrow="horizontal"
              className={`${Reset.list_extra} ${Reset.tel_input}`}
            >选择地址</List.Item>
          </Picker>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('address')}
            onErrorClick={() => {
              alert(getFieldError('address').join('、'));
            }}
            {...getFieldProps('address',{
              rules:[{required:true,message:'请输入地址'}]
            })}
            placeholder='地址'
          >地址</InputItem>
          <Picker  data={_companies} cols={1}  onOk={(e)=>{this.setState({sto_col:JSON.parse(e)})}}  
            error={!!getFieldError('cgj_company_id')}
            onErrorClick={() => {
              alert(getFieldError('cgj_company_id').join('、'));
            }}
          {...getFieldProps('cgj_company_id',{
            initialValue:_this.state.sto_col,
            rules:[{required:true}]
          })} className={`${Reset.tel_picker}`} extra={<span>选择品牌商</span>}>
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">品牌商</List.Item>
          </Picker>
          <Picker data={_material} cols={1}
            error={!!getFieldError('material')}
            onErrorClick={() => {
              alert(getFieldError('material').join('、'));
            }}
           {...getFieldProps('material',{
            rules:[{required:true}]
          })} className={`${Reset.tel_picker}`} extra={<span>选择材质</span>}>
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">材质</List.Item>
          </Picker>
          <Picker data={_regionNode} cols={2}
            error={!!getFieldError('regions_id')}
            onErrorClick={() => {
              alert(getFieldError('regions_id').join('、'));
            }}
            {...getFieldProps('regions_id',{
            rules:[{required:true}]
          })} className={`${Reset.tel_picker}`} extra={<span>选择渠道</span>}>
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">渠道</List.Item>
          </Picker>
          <InputItem
            error={!!getFieldError('surveyors')}
            onErrorClick={() => {
              alert(getFieldError('surveyors').join('、'));
            }}
            editable={false}
            value={this.state.surveyors.length===0?undefined:this.state.surveyors.name}
            placeholder='测量师傅'
            className={`${Reset.tel_input}`}
            onClick={()=>{this.setState({disable:true})}}
            onChange={()=>{this.setState({disable:true})}}
            {...getFieldProps('surveyors',{
              initialValue:this.state.surveyors.length===0?undefined:this.state.surveyors.name,
              rules:[{required:true,message:'请选择测量师傅'}]
            })}   >
            测量师傅
          </InputItem>
          <DatePicker
            className={`${Reset.tel_picker}`}
            mode="date"
            title="选择日期"
            extra={<span>预约测量时间</span>}
            clear
            error={!!getFieldError('booking_date')}
            onErrorClick={() => {
              alert(getFieldError('booking_date').join('、'));
            }}
            minDate={moment('2016-08-06 +0800', 'YYYY-MM-DD Z').utcOffset(8)}
            {...getFieldProps('booking_date', {
              rules:[{required:true}]
            })} 
          >
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">测量时间</List.Item>
          </DatePicker>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('square')}
            onErrorClick={() => {
              alert(getFieldError('square').join('、'));
            }}
            {...getFieldProps('square',{
              rules:[{required:true,message:'请输入面积'}]
            })}
            placeholder='预估面积(/m²)'
          >预估面积</InputItem>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('total')}
            onErrorClick={() => {
              alert(getFieldError('total').join('、'));
            }}
            {...getFieldProps('total',{
              rules:[{required:true,message:'请输入价格'}]
            })}
            placeholder='服务费(/元)'
          >服务费</InputItem>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('estimated_total')}
            onErrorClick={() => {
              alert(getFieldError('estimated_total').join('、'));
            }}
            {...getFieldProps('estimated_total',{
              rules:[{required:true,message:'请输入价格'}]
            })}
            placeholder='产品预估价格(/元)'
          >产品价格</InputItem>
          <List className={`${Reset.tel_list_header}`} renderHeader={() => '介绍人(选填项)'} style={{background:'#f5f5f9'}}>
            <InputItem
              className={`${Reset.tel_input}`}
              placeholder='介绍人姓名'
              {...getFieldProps('introducer_name', {
                
              })}
            >介绍人</InputItem>
            <InputItem
              className={`${Reset.tel_input}`}
              placeholder='介绍人电话号码'
              {...getFieldProps('introducer_tel', {
              })}
            >电话号码</InputItem>
            <InputItem
              disabled={true}
              className={`${Reset.tel_input}`}
              placeholder='介绍人返利'
              {...getFieldProps('rebate', {
                initialValue:'2%'
              })}
            >介绍人返利</InputItem>
          </List>
        </List>
        <Modal closable={true} onClose={(e)=>this.setState({disable:false})} visible={this.state.disable} title='搜索师傅'>
          <InputItem
            className={`${Reset.tel_input}`}
            placeholder='搜索师傅 可以输入手机号 或者名字进行搜索'
            onChange={(e)=>{this.handleSearch(e)}}
          >搜索师傅</InputItem>
          <List >
            {this.state.shifu.length===0?undefined:this.state.shifu.map((daa,index)=>{
              return <span onClick={(e)=>this.handleClick(e.target.innerHTML,daa)}  key={daa.id} style={{fontSize:'0.28rem',display:'inline-block',margin:5,padding:'10px 20px',background:'#efefef',color:'#333',borderRadius:25}}  data-index={daa.id}>{daa.name}</span>
            })}
          </List>
        </Modal>
        <AgreeItem checked={this.state.cgj_id} onClick={(e) => this.handleCheck(e)} key='cgj_id' data-seed='7'  className={`${Reset.label} ${Reset.tel_radio}`}> 
          下单至窗管家
        </AgreeItem>
        <Button  disabled={_falg} className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const OrderForm = createForm()(OrderEdit);
export default connect()(OrderForm)